<template>
  <div>
    <el-card class="el-card">
      <!--条件搜索-->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="账号" prop="username">
          <el-input
            placeholder="请输入账号"
            clearable
            size="default"
            v-model="queryParams.username"
          />
        </el-form-item>
        <el-form-item label="登录状态" prop="loginStatus">
          <el-select
            aria-placeholder="请选择登录状态"
            size="default"
            v-model="queryParams.loginStatus"
          >
            <el-option
              v-for="item in StatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.beginTime"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.endTime"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="querySearch">
            <template #icon>
              <i-ep-search />
            </template>
            查询
          </el-button>
          <el-button @click="resetQueryForm">
            <template #icon>
              <i-ep-refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!--操作按钮-->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            v-if="hasPermission('api.sysLoginInfo.batchDestroy')"
            plain
            type="danger"
            :disabled="multiple"
            @click="handBatchDestroy"
          >
            <template #icon>
              <i-ep-delete />
            </template>
            批量删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-if="hasPermission('api.sysLoginInfo.clean')"
            plain
            type="danger"
            :disabled="tableData.data.length <= 0"
            @click="handleClean"
          >
            <template #icon>
              <i-ep-delete />
            </template>
            清空
          </el-button>
        </el-col>
      </el-row>
      <!--列表-->
      <el-table
        border
        stripe
        class="w-full"
        header-cell-class-name="text-[#606266] !bg-[#eef1f6]"
        v-loading="tableData.loading"
        :data="tableData.data"
        @selection-change="handleSelectionChange"
      >
        <template #empty>
          <el-empty :image-size="100" description="暂无数据" />
        </template>
        <el-table-column
          type="selection"
          header-align="center"
        ></el-table-column>
        <el-table-column
          label="ID"
          header-align="center"
          v-if="false"
          prop="id"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="账号"
          prop="username"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="登录IP地址"
          prop="ip_address"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="登录地点"
          prop="login_location"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="浏览器类型"
          prop="browser"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="操作系统"
          prop="os"
        />
        <el-table-column
          header-align="center"
          label="登录状态"
          align="center"
          prop="login_status"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.loginStatus === 1" type="success">
              成 功
            </el-tag>
            <el-tag v-else-if="scope.row.loginStatus === 2" type="danger">
              失败
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="left"
          label="提示信息"
          prop="message"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="访问时间"
          prop="login_time"
        />
        <el-table-column
          header-align="center"
          align="center"
          fixed="right"
          label="操作"
          width="120"
        >
          <template #default="scope">
            <el-button
              v-if="hasPermission('api.sysLoginInfo.destroy')"
              type="danger"
              class="!ml-0"
              text
              @click="handDestroy(scope.row)"
            >
              <template #icon><i-ep-delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        class="justify-end"
        background
        @size-change="handleSizeChange()"
        @current-change="handleCurrentChange()"
        v-model:current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100, 500]"
        v-model:page-size="queryParams.pageSize"
        layout="total,sizes,prev,pager,next"
        :total="tableData.total"
        prev-text="上一页"
        next-text="下一页"
        :default-page-size="10"
        :pager-count="5"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { StatusList } from './login.data'
import { SearchParams, LoginItem } from '@/api/log/model/loginModel'
import { getList, destroy, batchDestroy, clean } from '@/api/log/login'
import { FormInstance } from 'element-plus'
import { useForm } from '@/hooks'
import { usePermission } from '@/hooks/permission'
const queryFormRef = ref<FormInstance>(null!)

const { resetForm } = useForm()
const { hasPermission } = usePermission()

//搜索参数
let queryParams = reactive<SearchParams>({
  pageNum: 1,
  pageSize: 10,
  username: '',
  loginStatus: 0,
  beginTime: '',
  endTime: '',
})

//表格及分页数据
const tableData = reactive({
  loading: true,
  total: 0,
  data: [],
})

//批量删除按钮是否可点击
let multiple = ref<boolean>(true)
//选中的数据
let batchIdArr = ref<number[]>([])

//获取列表数据
const getLogList = async () => {
  try {
    const { code, data, message } = await getList(queryParams)
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    tableData.total = data?.total || 0
    tableData.data = (data?.rows as never[]) || []
  } finally {
    tableData.loading = false
  }
}

//搜索
const querySearch = () => {
  getLogList()
}
//搜索重置
const resetQueryForm = () => {
  resetForm(queryFormRef.value)
  getLogList()
}

//page-size 改变时触发
const handleSizeChange = () => {
  getLogList()
}

//current-page 改变时触发
const handleCurrentChange = () => {
  getLogList()
}

//刪除
const handDestroy = async (row: LoginItem) => {
  ElMessageBox.confirm(`确定要删除编号为:${row.id}的登录日志吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await destroy({ id: row.id })
      if (code != 200) {
        ElMessage.error(`${message}`)
        return
      }
      ElMessage.success(`${message}`)
      getLogList()
      return
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

const handleSelectionChange = (selection: LoginItem[]) => {
  batchIdArr.value = selection.map((item: LoginItem) => item.id)
  multiple.value = !selection.length
}

const handBatchDestroy = async () => {
  const batchIds = batchIdArr.value
  ElMessageBox.confirm(`确定要删除编号为:${batchIds}的登录日志吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await batchDestroy({ ids: batchIds })
      if (code != 200) {
        ElMessage.error(`${message}`)
        return
      }
      ElMessage.success(`${message}`)
      getLogList()
      return
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

const handleClean = async () => {
  ElMessageBox.confirm(`确定要清空登录日志吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await clean()
      if (code != 200) {
        ElMessage.error(`${message}`)
        return
      }
      ElMessage.success(`清空成功`)
      getLogList()
      return
    })
    .catch(() => {
      ElMessage.info('取消操作')
    })
}

onMounted(() => {
  getLogList()
})
</script>

<style scoped></style>
